using System;
using System.Collections;
using Habanero.Base;
using Habanero.Base.Exceptions;

namespace FireStarterModeller.BO
{
    public class DMPropertyAutoIncrementingMustBeOfTypeInt : IBusinessObjectRule
    {
        private DMProperty _dmProperty;
       

//        public DMPropertyAutoIncrementingMustBeOfTypeInt(DMProperty dmProperty)
//        {
//            if (dmProperty == null) throw new ArgumentNullException("dmProperty");
//            _dmProperty = dmProperty;
//        }

        #region Implementation of IBusinessObjectRule

        /// <summary>
        /// Indicates whether the property value is valid against the rules
        /// </summary>
        /// <returns>
        /// Returns true if valid
        /// </returns>
        public bool IsValid()
        {
            throw new HabaneroApplicationException("The IsValid is no longer Valid you should use the IsValid(bo) method");
        }


        public bool IsValid(IBusinessObject bo)
        {
            _dmProperty = (DMProperty)bo;
            if (_dmProperty.PropertyType == null) return true;
            return !IsAutoIncrementingNonInteger();
        }

        private bool IsAutoIncrementingNonInteger()
        {
            return IsAutoIncrementing() && !IsInteger;
        }

        private bool IsAutoIncrementing()
        {
            return _dmProperty.AutoIncrementing.GetValueOrDefault();
        }

        private bool IsInteger
        {
            get
            {
                var propertyTypeName = _dmProperty.PropertyType.PropertyTypeName;
                return !String.IsNullOrEmpty(propertyTypeName) && propertyTypeName.StartsWith("Int");
            }
        }
        
        /// <summary>
        /// Returns the rule name
        /// </summary>
        public string Name
        {
            get { return "DMPropertyAutoIncrementingMustBeOfTypeInt"; }
        }

        /// <summary>
        /// Returns the error message for if the rule fails.
        /// </summary>
        public string Message
        {
            get { return "The Property '" + _dmProperty.ToString() + "' on class '" + _dmProperty.Class.ToString() + "' with Property Type '" + _dmProperty.PropertyType.ToString() + "' cannot be AutoIncrementing"; }
        }
        /// <summary>
        /// The <see cref="P:Habanero.Base.IBusinessObjectRule.ErrorLevel" /> for this BusinessObjectRule e.g. Warning, Error. 
        /// </summary>
        public ErrorLevel ErrorLevel
        {
            get { return Habanero.Base.ErrorLevel.Error; }
        }

        #endregion
    }
}